<template>
  <div class="app-container">
    <div class="filter-container clearfix">
      <el-button v-if="checkPermission(permissionRoles.notice_game_add)" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加公告</el-button>
    </div>
    <el-table ref="table" v-loading="listLoading" :data="list" border stripe style="width: 100%;" height="735">
      <el-table-column label="服务器" prop="sidStr" width="110px" align="center"></el-table-column>
      <el-table-column label="公告内容" prop="content" width="650px" align="center"></el-table-column>
      <el-table-column label="开始时间" prop="start_dt" width="140px" align="center"></el-table-column>
      <el-table-column label="结束时间" prop="end_dt" width="140px" align="center"></el-table-column>
      <el-table-column label="间隔时间" prop="interval" width="70px" align="center"></el-table-column>
      <el-table-column label="等级" prop="level" width="50px" align="center"></el-table-column>
      <el-table-column label="充值金额" prop="amount" width="70px" align="center"></el-table-column>
      <el-table-column label="优先级" prop="sort" width="50px" align="center"></el-table-column>
      <el-table-column label="状态" prop="status" width="60px" align="center">
        <template slot-scope="{row}">
          <span v-if="row.status === 1">进行中</span>
          <span v-else-if="row.status === 2">已结束</span>
          <span v-else>未开始</span>
        </template>
      </el-table-column>
      <el-table-column label="添加人" prop="create_user" width="60px" align="center"></el-table-column>
      <el-table-column align="center" label="操作" width="90px">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleView(scope)">查看</el-button>
          <el-button v-if="checkPermission(permissionRoles.notice_game_del)" type="text" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" :title="textMap[dialogType]" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="公告内容" prop="content">
          <el-input v-model="dataForm.content" :disabled="isFormDisabled" class="defaut-input" placeholder="填写公告内容" />
        </el-form-item>
        <el-form-item label="开始时间" prop="start_dt">
          <el-date-picker
            v-model="dataForm.start_dt"
            type="datetime"
            :disabled="isFormDisabled"
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="end_dt">
          <el-date-picker
            v-model="dataForm.end_dt"
            type="datetime"
            :disabled="isFormDisabled"
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item label="间隔时间" prop="interval">
          <el-input v-model="dataForm.interval" :disabled="isFormDisabled" class="defaut-input" placeholder="填写间隔时间 单位:秒" />
        </el-form-item>
        <el-form-item label="优先级" prop="sort">
          <el-input v-model="dataForm.sort" :disabled="isFormDisabled" class="defaut-input" placeholder="填写优先级" />
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input v-model="dataForm.amount" :disabled="isFormDisabled" class="defaut-input" placeholder="填写充值金额 不填则不限制" />
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-input v-model="dataForm.level" :disabled="isFormDisabled" class="defaut-input" placeholder="填写等级 不填则不限制 " />
        </el-form-item>
        <el-form-item label="服务器选择">
          <el-checkbox v-model="allServerChecked" :disabled="isFormDisabled" @change="checkAllServer">显示全服</el-checkbox>
        </el-form-item>
        <div class="server-box">
          <ul class="menu-sub">
            <li
              v-for="(sgit,index) in serverGroups"
              :key="index"
            >
              <el-checkbox
                v-model="sgit.flag"
                :indeterminate="itemIndeterminate(sgit)"
                :disabled="isFormDisabled"
                @change="(val) => handleCheckAll(val, sgit)"
              >{{ sgit.sgname }}</el-checkbox>
              <el-checkbox-group
                v-model="selectedData"
                style="padding-left: 30px;"
                @change="handleChanges(sgit)"
              >
                <el-checkbox
                  v-for="sgits in sgit.children"
                  :key="sgits.sid"
                  :disabled="isFormDisabled"
                  :label="sgits.sid"
                >{{ sgits.name }}</el-checkbox>
              </el-checkbox-group>
            </li>
          </ul>
        </div>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" :disabled="isFormDisabled" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import waves from '@/directive/waves' // 实现点击波浪纹
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getServerListGroup } from '@/api/ops'
import { deepClone } from '@/utils'
import { handleGameNotice, getGameNotice, deleteGameNotice } from '@/api/gm'

const defaultItem = {
  id: '',
  content: '',
  start_dt: '',
  end_dt: '',
  interval: '',
  sort: '',
  level: '',
  amount: '',
  sid: []
}
export default {
  name: 'NoticeGame',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      permissionRoles: this.$store.state.user.permissionRoles,
      list: [],
      total: 0,
      listLoading: false,
      dataForm: Object.assign({}, defaultItem),
      allServerChecked: false,
      isFormDisabled: false,
      selectedData: [],
      serverGroups: [],
      rules: {
        content: [{ required: true, message: '请填写内容', trigger: 'blur' }],
        start_dt: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
        end_dt: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
        interval: [{ required: true, message: '请填写间隔时间', trigger: 'blur' }],
        sort: [{ required: true, message: '请填写优先级', trigger: 'blur' }]
      },
      listQuery: {
        page: 1,
        limit: 200
      },
      dialogVisible: false,
      dialogType: 'new',
      textMap: {
        view: '查看',
        new: '新增'
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermission,
    async getList() {
      const query = this.listQuery
      this.listLoading = true
      const res = await getGameNotice(query)
      this.listLoading = false
      this.list = res.data.items
      this.total = res.data.total
    },
    handleFilter() {
      this.getList()
    },
    async serverListGroup(val) {
      getServerListGroup({ all: val }).then(res => {
        this.serverGroups = res.data
      })
    },
    handleAdd() {
      this.dataForm = Object.assign({}, defaultItem)
      this.dialogType = 'new'
      this.dialogVisible = true
      this.isFormDisabled = false
      this.serverListGroup(false)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleView(scope) {
      this.dialogType = 'view'
      this.dialogVisible = true
      this.isFormDisabled = true
      this.serverListGroup(false)
      const s = scope.row.sid.split(',')
      this.dataForm = deepClone(scope.row)
      this.selectedData = s.map(Number)
      if (this.selectedData.some(number => number <= 1000)) {
        this.allServerChecked = true
        this.checkAllServer()
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === 'edit'
          this.dataForm.sid = this.selectedData
          handleGameNotice(this.dataForm).then(response => {
            if (response.status) {
              if (isEdit) {
                for (let index = 0; index < this.list.length; index++) {
                  if (this.list[index].id === this.dataForm.id) {
                    this.list.splice(index, 1, Object.assign({}, this.dataForm))
                    break
                  }
                }
              } else {
                this.list.push(response.data)
              }
              this.dialogVisible = false
              this.getList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('你确定要删除此行数据吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteGameNotice(row.id)
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => { console.error(err) })
    },
    // 全选
    handleCheckAll(val, item) {
      // 过滤掉没有选中的数据，item.child中不包含v时返回-1
      const next = item.children.map(item => item.sid)
      const filterArr = this.selectedData.filter(
        (v) => next.indexOf(v) === -1
      )
      this.selectedData = val ? filterArr.concat(next) : filterArr
    },
    itemIndeterminate(item) {
      const infoLists = item.children.map(ite => ite.sid)
      return (
        infoLists.some((v) => this.selectedData.indexOf(v) > -1) &&
        !infoLists.every((v) => this.selectedData.indexOf(v) > -1)
      )
    },
    // 勾选变化方法
    handleChanges(val) {
      const infoLists = val.children.map(ite => ite.sid)
      infoLists.every((v) => {
        if (this.selectedData.indexOf(v) > -1) {
          val.flag = true
        } else {
          val.flag = false
        }
      })
    },
    checkAllServer() {
      this.serverListGroup(this.allServerChecked)
    }
  }
}
</script>
